<template>
 <div class="count-adjust">
   <div class="adjust-inner">
     <el-radio-group v-model="symbolModel">
       <el-radio-button label="+" v-if="showSymbol.includes('+')">增</el-radio-button>
       <el-radio-button label="-" v-if="showSymbol.includes('-')">减</el-radio-button>
     </el-radio-group>
     <el-input-number v-model="valueModel" :min="min" :max="99999999" class="adjust-input"></el-input-number>
   </div>
 </div>
</template>

<script lang="ts" setup>
import {WritableComputedRef} from "vue";

const props = withDefaults(defineProps<{
  modelValue: number,
  min?: number,
  showSymbol?: "+-" | "+" | "-"
}>(), {
  modelValue: 0,
  min: 0,
  showSymbol: "+-"
})

const emits = defineEmits<{
  (e: 'update:model-value', value: number): void;
  (e: 'change', value: number): void;
}>()

const modelValue:WritableComputedRef<number> = computed({
  get() {
    return props.modelValue
  },
  set(newValue) {
    emits("update:model-value", newValue)
  }
})

const symbolModel = ref("+")
const valueModel = ref(0)

watch(symbolModel, (newValue) => {
  console.log("symbolModel", newValue)
  if (isNaN(Number(valueModel.value))) {
    modelValue.value = 0
    valueModel.value = 0
  } else {
    modelValue.value = Number(symbolModel.value + valueModel.value)
  }

  emits("change", modelValue.value)
})
watch(valueModel, (newValue) => {
  // console.log('valueModel', newValue)
  // debugger
  if (isNaN(Number(valueModel.value))) {
    modelValue.value = 0
    valueModel.value = 0
  } else {
    modelValue.value = Number(symbolModel.value + valueModel.value)
  }

  emits("change", modelValue.value)
})

watch(modelValue, (newValue) => {
  console.log('modelValue', newValue)
  if (isNaN(Number(newValue))) {
    valueModel.value = 0
  } else {
    if (Number(newValue) < 0) {
      symbolModel.value = '-'
      valueModel.value = Math.abs(Number(newValue))
    } else if (Number(newValue) === 0) {
      // symbolModel.value = '+'
      valueModel.value = 0
    } else {
      symbolModel.value = '+'
      valueModel.value = Math.abs(Number(newValue))
    }
  }
}, {
  immediate: true
})
</script>

<style scoped lang="scss">
.count-adjust {
  display: inline-block;
}

.adjust-inner {
  display: flex;
  align-items: center;
  width: 300px;
}

.adjust-input {
  margin-left: 10px;
  flex: 1;
}
</style>
